import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { Box } from '@alifd/next';
import { observer } from 'mobx-react-lite';
import { t } from '@lingui/macro';
import dayjs from 'dayjs';
import styles from './PieChart.module.scss';
import { useStore } from '@/hooks';

const RangePreset = {};
RangePreset[t`昨日`] = [dayjs().subtract(1, 'day'), dayjs()];
RangePreset[t`近一周`] = [dayjs().add(-7, 'day'), dayjs()];
RangePreset[t`近二周`] = [dayjs().add(-15, 'day'), dayjs()];

const _barWidth = '10%';

function SubGroupInfo({ title, data }) {
  const chartRef = useRef(null);
  const { ruleStore } = useStore();
  useEffect(() => {
    (async () => {
      const chartInstance = echarts.init(chartRef.current);
      const option = {
        tooltip: {
          trigger: 'item',
        },
        legend: {
          type: 'scroll',
          orient: ruleStore._isPhone ? 'horizontal' : 'vertical',
          right: 0,
          top: 20,
          bottom: 20,
          data: data?.map((p) => p.name),
          formatter: (name) => {
            const item = data.find((p) => p.name === name);
            const itemTotal = data.find((p) => p.name == '其他');
            const value = item ? item.value : 0;
            const percentage = itemTotal?.total ? ((value / itemTotal?.total) * 100).toFixed(2) : 0; // 计算百分比
            return `${name}: ${value} (${percentage}%)`; // 自定义格式
          },
        },
        series: [
          {
            data: data || [],
            type: 'pie',
            radius: ruleStore._isPhone ? ['20%', '40%'] : ['40%', '70%'],
            avoidLabelOverlap: false,
            center: ruleStore._isPhone ? ['50%', '50%'] : ['36%', '42%'], // 调整水平位置
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold',
                formatter: '{b}: {d}%', // {b} 为名字，{d} 为百分比
                // position: 'outside', // 将标签放置在外部
              },
            },
          },
        ],
      };
      chartInstance.setOption(option);
    })();
  }, [data]);

  return (
    <Box direction="column" justify="center" align="center">
      <div ref={chartRef} className={styles.charts} />
      <div className={styles.title}>
        <span>{title}</span>
      </div>
    </Box>
  );
}

export default observer(SubGroupInfo);
